// import { uploadFileApi } from '@/api/common'
import { FileSaveFolderName } from '@/common'
import { useLoadingStore } from '@/stores/loading'
import { useRouterStore } from '@/stores/router'
import { ElMessage } from 'element-plus'
import { pickBy } from 'lodash'
import { unref } from 'vue'
//检查手机号
const checkMobile = (mobile = '') => /^(\+86)?1\d{10}$/.test(mobile)

//检查邮箱
const checkEmail = (email = '') =>
    /^[\w-]+(\.[\w-]+)*@[A-Za-z0-9]+((.|-|_)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(
        email
    )

// 检查密码(长度大于等于6位，包含数字、字母、特殊字符)
const checkPassword = (password = '', minLength) => {
    const hasNumber = /\d/
    const hasLetter = /[a-zA-Z]/
    // 特殊字符正则表达式，不包含空格
    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/

    // 检查长度
    if (password.length < minLength) {
        return {
            status: false,
            message: `密码长度至少${minLength}位`
        }
    }

    // 检查是否包含数字
    if (!hasNumber.test(password)) {
        return {
            status: false,
            message: `密码需包含至少一个数字`
        }
    }

    // 检查是否包含字母
    if (!hasLetter.test(password)) {
        return {
            status: false,
            message: `密码需包含至少一个字母`
        }
    }

    // 检查是否包含特殊字符（不包含空格）
    if (!hasSpecialChar.test(password)) {
        return {
            status: false,
            message: `密码需包含至少一个特殊字符`
        }
    }

    // 如果所有检查都通过，则返回 true
    return {
        status: true
    }
}

// 隐藏手机号中间四位
function mixMobile(mobile = '') {
    return mobile.substring(0, 3) + '****' + mobile.substring(7)
}

export function checkType(obj, type) {
    type = type.charAt(0).toUpperCase() + type.slice(1)
    return Object.prototype.toString.call(obj) === `[object ${type}]`
}

// 整理url参数
function createUrlParams(obj = {}, prefix = '') {
    // 过滤空数组
    obj = pickBy(obj, (val) => (Array.isArray(val) ? val.length : true))
    if (!checkType(obj, 'object')) {
        return obj
    }
    const attrs = []
    for (const [key, val] of Object.entries(obj)) {
        attrs.push(key)
    }
    return attrs.reduce((query, attr, index) => {
        // get方式如果是null和undefined
        if (obj[attr] === null || obj[attr] === undefined) {
            obj[attr] = ''
        }
        // 判断是否是第一层第一个循环
        if (index === 0 && !prefix) {
            query += '?'
        }
        if (checkType(obj[attr], 'object') || checkType(obj[attr], 'array')) {
            query += `${attr}=${encodeURIComponent(JSON.stringify(obj[attr]))}`
        } else {
            query += `${attr}=${encodeURIComponent(obj[attr])}`
        }
        // 判断是否是第一层最后一个循环
        if (index !== attrs.length - 1) {
            query += '&'
        }
        return query
    }, '')
}

// 获取上传文件名
export const getFileName = (url = '') =>
    url?.substring(url?.lastIndexOf('/') + 1)

// 回去文件格式
export const getFileExtName = (str = '') => {
    const extIndex = str.lastIndexOf('.')
    const FileExtName = str.substring(extIndex + 1) || ''
    return FileExtName
}

// 新链接打开
const openUrlBlank = (url) => {
    window.open(url, '_blank')
}

//四舍五入两位小数
const getRound = (num, check) => {
    if (check) {
        if (num === '' || num === undefined || num === null) {
            return num
        }
    }
    return (Math.round((num || 0) * 100) / 100).toFixed(2)
}

// 获取百分比
const getPercent = (num, check) => {
    if (check) {
        if (num === '' || num === undefined || num === null) {
            return num
        }
    }
    return (Math.round((num || 0) * 100 * 100) / 100).toFixed(2)
}

/**
 * @description 判读是否为外链
 * @param path
 * @returns {boolean}
 */
export function isExternal(path = '') {
    return /^(https?:|wss?:|mailto:|tel:|\/\/)/.test(path)
}

// 文件对象转base64  file是file对象
export function getBase64(file) {
    return new Promise((resolve, reject) => {
        let reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
            imgResult = reader.result
        }
        reader.onerror = function (error) {
            reject(error)
        }
        reader.onloadend = function () {
            resolve(imgResult)
        }
    })
}

// 权限递归循环得出被选中的IDX数组
export const findCheckedIds = (nodes) => {
    const checkedIds = []
    if (nodes?.length) {
        function traverse(nodes) {
            for (const node of nodes) {
                if (node.IsChecked) {
                    checkedIds.push(node.IDX)
                }
                if (node.SubList && node.SubList.length > 0) {
                    traverse(node.SubList)
                }
            }
        }

        traverse(nodes)
    }

    return checkedIds
}

// 将list转换为lable,value,children ->树状结构
export function transformList(list, key) {
    // 基础情况，检查传入的 list 是否为空
    if (!Array.isArray(list)) {
        return []
    }

    // 遍历 list，将每个元素转换成 { label, value, children } 格式
    return list.map((item) => {
        // 创建基本结构
        const transformedItem = {
            label: item.DisplayName,
            value: item.IDX,
            children: []
        }

        // 如果存在 SubList 字段，递归调用自身
        if (item[key] && Array.isArray(item[key])) {
            transformedItem.children = transformList(item[key])
        }

        return transformedItem
    })
}

// 将扁平数据组织成 -> 树结构
export function formatMenuTree(data) {
    const map = {}
    const roots = []

    // 首先，将每一个节点存储在一个以 id 为键的映射中
    data.forEach((item) => {
        map[item.meta.id] = { ...item, children: [] } // 初始化节点并添加 children 属性
    })

    // 然后，构建树
    data.forEach((item) => {
        if (item.meta.parentId === 0) {
            roots.push(map[item.meta.id]) // 如果是根节点，直接加入根节点数组
        } else {
            map[item.meta.parentId].children.push(map[item.meta.id]) // 否则将此节点添加到父节点的 children 中
        }
    })

    return roots // 返回最终的树形结构
}

// 对树结构的每一层都进行排序
export function sortTree(nodes) {
    nodes.sort((a, b) => a.meta.order - b.meta.order)
    nodes.forEach((node) => {
        if (node.children?.length > 0) {
            sortTree(node.children)
        }
    })
}

// 树形结构递归找到子级对应的父级和自己
export function findParentChain(tree, targetId, result = []) {
    // Helper function to recursively search the tree
    function search(node, targetId, path) {
        // Add current node's id to the path
        path.push(node.IDX)
        // Check if we've reached the target node
        if (node.IDX === targetId) {
            result.push([...path].reverse().join(','))
            return true // Found the target, stop searching further
        }

        // Continue searching in the SubList
        if (node.SubList && node.SubList.length > 0) {
            for (let child of node.SubList) {
                if (search(child, targetId, path)) {
                    return true // Target found in one of the SubList
                }
            }
        }

        // If not found, backtrack
        path.pop()
        return false
    }

    // Start searching from the root of the tree
    for (let node of tree) {
        search(node, targetId, [])
    }
    if (result && result[0]) {
        return result[0]
            .split(',')
            .map((i) => Number(i))
            .reverse()
    }
}

// 查找idx 在list中以及寻找父级对象 直到找到直到达到 ParentID 为 0 的节点
// 返回[{},{}]扁平化数组
export function findHierarchy(list, idx) {
    const result = []
    let currentIdx = idx

    while (currentIdx !== 0) {
        const found = list.find((item) => item.IDX === currentIdx)
        if (found) {
            result.push(found)
            currentIdx = found.ParentID
        } else {
            break // 如果找不到，退出循环
        }
    }

    return result.reverse() // 返回结果反向排序，从根节点到目标节点
}

// 路由数递归遍历找target的children的第一项，没有的话返回当前项,key
export function findItemByName(data, key, target) {
    for (const item of data) {
        // 检查当前项 id 是否匹配
        if (item[key] === target) {
            let currentItem = item

            // 当有子项且子项长度大于0时，逐层获取第一项
            while (currentItem.children && currentItem.children.length > 0) {
                currentItem = currentItem.children[0]
            }

            return currentItem // 返回找到的项目
        }

        // 如果当前项有 children，则递归查找
        if (item.children) {
            const foundItem = findItemByName(item.children, key, target)
            if (foundItem) {
                return foundItem // 返回找到的项目
            }
        }
    }
    return null // 如果没有找到目标 id，则返回 null
}

// 如果够6位去全部，不够则补0
export function formatNumber(num, size) {
    // 将数字转换为字符串
    var numStr = num.toString()

    // 检查长度并补零
    if (numStr.length < size) {
        // 使用 '000000' 作为基础字符串，然后截取右侧6位
        return ('000000' + numStr).slice(-1 * size)
    } else {
        return numStr
    }
}

// 清除某个表单项校验propList是prop的数组 ['prop1', prop2]
export const clearValidate = (formRef, propList) => {
    unref(formRef).$refs.form.clearValidate(propList)
}

// 给表单某项增加校验propList是prop的数组 ['prop1', prop2]
export const checkValidateField = async (formRef, propList) => {
    try {
        await unref(formRef).$refs.form.validateField(propList)
    } catch (error) {}
}

// 返回table选择的项
export const setTableCurrentRow = (tableRef, row) => {
    unref(tableRef).$refs.multipleTable.setCurrentRow(row)
}

// 返回table选择的项
export const getTableselectedDataList = (tableRef) => {
    return unref(tableRef).$refs.multipleTable.getSelectionRows()
}

// 清除表格所选项
export const clearSelectionDataList = (tableRef) => {
    return unref(tableRef).$refs.multipleTable.clearSelection()
}

// 清除某个表单项校验propList是prop的数组 ['prop1', prop2]
export const doSearch = (formRef) => {
    unref(formRef).doSearch()
}

export const doReset = (formRef) => {
    unref(formRef).doResetForm()
}

export const uploadFile = (data) => {
    // const loadingStore = useLoadingStore()
    // return new Promise((reslove, reject) => {
    //     loadingStore.showFullLoading = true
    //     uploadFileApi(data)
    //         .then((res) => {
    //             loadingStore.showFullLoading = false
    //             if (res?.Code == '200' && res.Data) {
    //                 reslove(res.Data)
    //             } else {
    //                 reject()
    //                 ElMessage.error(res.Message)
    //             }
    //         })
    //         .catch((e) => {
    //             reject()
    //             loadingStore.showFullLoading = false
    //             console.log(e)
    //         })
    // })
}

// 上传图片, IsChangeImage默认为0不转图片
export const doUploadFileData = (raw, IsChangeImage = 0) => {
    return new Promise(async (resolve, reject) => {
        // 上传base64图片
        try {
            const base64 = await getBase64(raw)
            const extIndex = raw.name.lastIndexOf('.')
            const FileExtName = getFileExtName(raw.name)
            const url = await uploadFile({
                Base64String: base64,
                FileExtName,
                FileName: raw.name.substring(extIndex, -1) || '',
                FileSaveFolderName,
                FileType:
                    FileExtName.toLocaleLowerCase() === 'pdf' ? 'PDF' : 'IMAGE',
                IsChangeImage
            })
            resolve({
                name: raw.name,
                url
            })
        } catch (e) {
            console.log(e)
            reject()
        }
    })
}

export const toUrl = (routerData) => {
    const routerStore = useRouterStore()
    routerStore.router.push(routerData)
}

// 检查一个对象的某个属性是否和list中的某个属性值相等
export const checkIsExist = (list, obj, prop) => {
    return list.some((i) => i[prop] === obj[prop])
}

export {
    checkMobile,
    checkEmail,
    checkPassword,
    openUrlBlank,
    createUrlParams,
    mixMobile,
    getRound,
    getPercent
}
